# -*- coding: utf-8 -*-
"""
乒乓球培训管理系统 - 学员表单

学员管理相关的表单定义
包括学员搜索、编辑、注销等表单
"""

from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from wtforms import (
    StringField, TextAreaField, SelectField, IntegerField,
    BooleanField, HiddenField, ValidationError
)
from wtforms.validators import (
    DataRequired, Length, Email, NumberRange, Optional,
    Regexp
)
from flask_login import current_user
from sqlalchemy import and_, or_

from app.models.user import User
from app.models.campus import Campus


class StudentSearchForm(FlaskForm):
    """学员搜索表单"""

    keyword = StringField(
        '关键词',
        validators=[Optional(), Length(max=50)],
        render_kw={
            'placeholder': '搜索学员姓名、手机号...',
            'class': 'form-control'
        }
    )

    campus_id = SelectField(
        '所属校区',
        coerce=int,
        choices=[],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    status = SelectField(
        '状态',
        choices=[
            ('', '全部状态'),
            ('active', '活跃'),
            ('inactive', '不活跃')
        ],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    has_coach = SelectField(
        '是否有教练',
        choices=[
            ('', '全部'),
            ('yes', '有教练'),
            ('no', '无教练')
        ],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    sort_by = SelectField(
        '排序方式',
        choices=[
            ('created_at_desc', '注册时间（新到旧）'),
            ('created_at_asc', '注册时间（旧到新）'),
            ('name_asc', '姓名（A-Z）'),
            ('name_desc', '姓名（Z-A）'),
            ('reservation_count_desc', '预约次数（多到少）')
        ],
        default='created_at_desc',
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 根据用户权限设置校区选择
        campus_choices = [(0, '全部校区')]

        if current_user.is_authenticated:
            if current_user.is_super_admin():
                # 超级管理员可以看到所有校区
                campuses = Campus.query.all()
                campus_choices.extend([(campus.id, campus.name) for campus in campuses])
            elif current_user.is_campus_admin():
                # 校区管理员只能看到自己的校区
                if current_user.campus_id:
                    campus = Campus.query.get(current_user.campus_id)
                    if campus:
                        campus_choices = [(0, '全部校区'), (campus.id, campus.name)]

        self.campus_id.choices = campus_choices


class StudentEditForm(FlaskForm):
    """学员编辑表单"""

    real_name = StringField(
        '真实姓名',
        validators=[
            DataRequired(message='请输入真实姓名'),
            Length(2, 50, message='姓名长度必须在2-50个字符之间')
        ],
        render_kw={
            'placeholder': '请输入真实姓名',
            'class': 'form-control'
        }
    )

    phone = StringField(
        '手机号',
        validators=[
            DataRequired(message='请输入手机号'),
            Regexp(r'^1[3-9]\d{9}$', message='请输入正确的手机号格式')
        ],
        render_kw={
            'placeholder': '请输入11位手机号',
            'class': 'form-control'
        }
    )

    email = StringField(
        '邮箱',
        validators=[
            Optional(),
            Email(message='请输入正确的邮箱格式'),
            Length(max=100, message='邮箱长度不能超过100个字符')
        ],
        render_kw={
            'placeholder': '请输入邮箱地址（可选）',
            'class': 'form-control'
        }
    )

    gender = SelectField(
        '性别',
        choices=[
            ('', '请选择'),
            ('male', '男'),
            ('female', '女')
        ],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    age = IntegerField(
        '年龄',
        validators=[
            Optional(),
            NumberRange(min=3, max=80, message='年龄必须在3-80之间')
        ],
        render_kw={
            'placeholder': '请输入年龄',
            'class': 'form-control',
            'min': '3',
            'max': '80'
        }
    )

    campus_id = SelectField(
        '所属校区',
        coerce=int,
        choices=[],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    photo = FileField(
        '头像',
        validators=[
            Optional(),
            FileAllowed(['jpg', 'jpeg', 'png', 'gif'], '只允许上传图片文件')
        ],
        render_kw={'class': 'form-control'}
    )

    status = SelectField(
        '状态',
        choices=[
            ('active', '活跃'),
            ('inactive', '不活跃')
        ],
        validators=[DataRequired(message='请选择状态')],
        render_kw={'class': 'form-select'}
    )

    notes = TextAreaField(
        '备注',
        validators=[
            Optional(),
            Length(max=500, message='备注不能超过500个字符')
        ],
        render_kw={
            'placeholder': '可添加关于学员的备注信息',
            'class': 'form-control',
            'rows': '3'
        }
    )

    def __init__(self, student=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.student = student

        # 根据用户权限设置校区选择
        campus_choices = [(0, '请选择校区')]

        if current_user.is_authenticated:
            if current_user.is_super_admin():
                # 超级管理员可以选择所有校区
                campuses = Campus.query.all()
                campus_choices.extend([(campus.id, campus.name) for campus in campuses])
            elif current_user.is_campus_admin():
                # 校区管理员只能选择自己的校区
                if current_user.campus_id:
                    campus = Campus.query.get(current_user.campus_id)
                    if campus:
                        campus_choices = [(0, '请选择校区'), (campus.id, campus.name)]

        self.campus_id.choices = campus_choices

    def validate_phone(self, field):
        """验证手机号唯一性"""
        user = User.query.filter_by(phone=field.data).first()
        if user and (not self.student or user.id != self.student.id):
            raise ValidationError('该手机号已被注册')

    def validate_email(self, field):
        """验证邮箱唯一性"""
        if field.data:
            user = User.query.filter_by(email=field.data).first()
            if user and (not self.student or user.id != self.student.id):
                raise ValidationError('该邮箱已被注册')

    def validate_campus_id(self, field):
        """验证校区权限"""
        if field.data and current_user.is_campus_admin():
            if current_user.campus_id != field.data:
                raise ValidationError('您只能设置学员到自己管理的校区')


class StudentProfileForm(FlaskForm):
    """学员档案编辑表单（学员自己使用）"""

    real_name = StringField(
        '真实姓名',
        validators=[
            DataRequired(message='请输入真实姓名'),
            Length(2, 50, message='姓名长度必须在2-50个字符之间')
        ],
        render_kw={
            'placeholder': '请输入真实姓名',
            'class': 'form-control'
        }
    )

    email = StringField(
        '邮箱',
        validators=[
            Optional(),
            Email(message='请输入正确的邮箱格式'),
            Length(max=100, message='邮箱长度不能超过100个字符')
        ],
        render_kw={
            'placeholder': '请输入邮箱地址（可选）',
            'class': 'form-control'
        }
    )

    gender = SelectField(
        '性别',
        choices=[
            ('', '请选择'),
            ('male', '男'),
            ('female', '女')
        ],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    age = IntegerField(
        '年龄',
        validators=[
            Optional(),
            NumberRange(min=3, max=80, message='年龄必须在3-80之间')
        ],
        render_kw={
            'placeholder': '请输入年龄',
            'class': 'form-control',
            'min': '3',
            'max': '80'
        }
    )

    photo = FileField(
        '头像',
        validators=[
            Optional(),
            FileAllowed(['jpg', 'jpeg', 'png', 'gif'], '只允许上传图片文件')
        ],
        render_kw={'class': 'form-control'}
    )


class StudentBatchForm(FlaskForm):
    """学员批量操作表单"""

    student_ids = HiddenField(
        '学员ID列表',
        validators=[DataRequired(message='请选择要操作的学员')]
    )

    action = SelectField(
        '批量操作',
        choices=[
            ('', '请选择操作'),
            ('activate', '批量激活'),
            ('deactivate', '批量停用'),
            ('transfer_campus', '转移校区'),
            ('delete', '批量删除')
        ],
        validators=[DataRequired(message='请选择批量操作类型')],
        render_kw={'class': 'form-select'}
    )

    target_campus_id = SelectField(
        '目标校区',
        coerce=int,
        choices=[],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 根据用户权限设置校区选择
        campus_choices = [(0, '请选择校区')]

        if current_user.is_authenticated:
            if current_user.is_super_admin():
                campuses = Campus.query.filter_by(status='active').all()
                campus_choices.extend([(campus.id, campus.name) for campus in campuses])
            elif current_user.is_campus_admin():
                if current_user.campus_id:
                    campus = Campus.query.get(current_user.campus_id)
                    if campus:
                        campus_choices = [(0, '请选择校区'), (campus.id, campus.name)]

        self.target_campus_id.choices = campus_choices


class StudentDeleteForm(FlaskForm):
    """学员删除确认表单"""

    student_id = HiddenField(
        '学员ID',
        validators=[DataRequired()]
    )

    confirm_text = StringField(
        '确认删除',
        validators=[
            DataRequired(message='请输入确认文本')
        ],
        render_kw={
            'placeholder': '请输入"确认删除"',
            'class': 'form-control'
        }
    )

    delete_reason = TextAreaField(
        '删除原因',
        validators=[
            Optional(),
            Length(max=255, message='删除原因不能超过255个字符')
        ],
        render_kw={
            'placeholder': '请说明删除该学员的原因（可选）',
            'class': 'form-control',
            'rows': '3'
        }
    )

    def validate_confirm_text(self, field):
        """验证确认文本"""
        if field.data != '确认删除':
            raise ValidationError('请输入正确的确认文本：确认删除')


class StudentCoachApplicationForm(FlaskForm):
    """学员申请教练表单"""

    coach_id = SelectField(
        '选择教练',
        coerce=int,
        choices=[],
        validators=[DataRequired(message='请选择教练')],
        render_kw={'class': 'form-select'}
    )

    apply_note = TextAreaField(
        '申请说明',
        validators=[
            Optional(),
            Length(max=255, message='申请说明不能超过255个字符')
        ],
        render_kw={
            'placeholder': '请简要说明选择该教练的原因或期望（可选）',
            'class': 'form-control',
            'rows': '3'
        }
    )

    def __init__(self, student=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.student = student

        # 获取可申请的教练列表
        coach_choices = [('', '请选择教练')]

        if student and student.campus_id:
            # 只显示同校区的活跃教练
            from app.models.user import User
            coaches = User.query.filter_by(
                role='coach',
                status='active',
                campus_id=student.campus_id
            ).all()

            # 过滤掉已经有关系的教练
            if coaches:
                from app.models.relation import StudentCoachRelation
                existing_relations = StudentCoachRelation.query.filter_by(
                    student_id=student.id
                ).all()
                existing_coach_ids = {rel.coach_id for rel in existing_relations}

                available_coaches = [
                    coach for coach in coaches
                    if coach.id not in existing_coach_ids
                ]

                coach_choices.extend([
                    (coach.id, f'{coach.real_name} - {coach.coach_level}级教练 - {coach.hourly_rate}元/小时')
                    for coach in available_coaches
                ])

        self.coach_id.choices = coach_choices